package org.abettor.angleworm.db;

import java.io.File;
import java.util.Properties;

import org.abettor.util.Environment;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Hibernate的Session工厂
 * @author abettor
 */
public abstract class HibernateSessionFactory
{
	private static String CONFIG_FILE_LOCATION = "org/abettor/angleworm/db/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static final Configuration cfg = new Configuration();
	private static SessionFactory sessionFactory;
	private static byte[] lock = new byte[0];

	/**
	 * 获取当前线程所使用的Session对象。
	 * 如果没有，就创建一个出来。
	 * @throws HibernateException
	 */
	public static Session getSession() throws HibernateException
	{
		Session session = threadLocal.get();
		if(session == null || ! session.isOpen())
		{
			if(sessionFactory == null)
			{
				try
				{
					synchronized(lock)
					{
						String dbFile = Environment.getUserDataDirectory() + File.separator + "userdata.sqlite";
						cfg.configure(CONFIG_FILE_LOCATION);
						Properties prop = cfg.getProperties();
						String url = "jdbc:sqlite:" + dbFile;
						prop.setProperty("hibernate.connection.url", url);
					}
					sessionFactory = cfg.buildSessionFactory();
				}
				catch(Exception e)
				{
					e.printStackTrace();
					return null;
				}
			}
			session = (sessionFactory != null) ? sessionFactory.openSession() : null;
			threadLocal.set(session);
		}

		return session;
	}

	/**
	 * 关闭当前线程使用的Session
	 * @throws HibernateException
	 */
	public static void releaseSession() throws HibernateException
	{
		Session session = threadLocal.get();
		threadLocal.set(null);
		if(session != null)
		{
			session.close();
		}
	}
}
